interface IItem<T> {
  [key: number]: T
}

class Queue<T> {
  count: number
  lowerestCount: number
  items: IItem<T>

  constructor() {
    this.count = 0
    this.lowerestCount = 0
    this.items = {}
  }

  // 向队列尾部添加一个(或多个)新的项。
  enqueue(ele: T | T[]): void {
    const newArr = []
    if (!(ele instanceof Array)) {
      this.items[this.count++] = ele
    } else {
      for (let i = 0; i < ele.length; i++) {
        this.items[this.count++] = ele[i]
      }
    }
  }
  // 移除队列的第一项(即排在队列最前面的项)并返回被移除的元素。
  dequeue(): T | undefined {
    let head: T
    if (this.isEmpty()) {
      return undefined
    }

    head = this.items[this.lowerestCount]
    delete this.items[this.lowerestCount]
    this.lowerestCount++
    return head
  }
  // 返回队列中第一个元素——最先被添加，也将是最先被移除的元素。队列不做
  peek(): T | undefined {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.lowerestCount]
  }
  // 如果队列中不包含任何元素，返回 true，否则返回 false。

  isEmpty(): boolean {
    return this.size() === 0
  }
  // 返回队列包含的元素个数，与数组的 length 属性类似。
  size(): number {
    return this.count - this.lowerestCount
  }
  // 清空队列
  clear(): void {
    this.lowerestCount = 0
    this.count = 0
    this.items = {}
  }
  // 创建 toString 方法
  toString(): string {
    if (this.isEmpty()) {
      return ''
    }
    let lowerestCount = this.lowerestCount
    let ret: string = this.items[lowerestCount++] + ''
    while (lowerestCount < this.count) {
      ret = `${ret},${this.items[lowerestCount++]}`
    }
    return ret
  }
}

export default Queue
